package org.jinxing.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jinxing.controller.IndexController;
import org.jinxing.model.UsersInfo;
import org.jinxing.utils.ServletUtils;

public class LgFilter implements Filter{
	protected static String className = LgFilter.class.getName();
	protected static Log logger = LogFactory.getLog(className);//日志对象
	
	private String[] noFilters = null;
	@Override
	public void destroy() {
		noFilters = null;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain nextFilter) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse res = (HttpServletResponse)response;
		String path = req.getRequestURI();
		if(null != noFilters){
			for(String s:this.noFilters){
				if(path.contains(s)){
					nextFilter.doFilter(request, response);
					return;
				}
			}
		}
		UsersInfo user = ServletUtils.getLgUser(req);
		if(null == user){
			logger.info("<|>"+className+"<|>doFilter<|>未登录<|>");
			String backUrl = path;
			if(null != req.getQueryString()){
				backUrl += "?"+req.getQueryString();
			}
			backUrl = "/v1/lg/lgIn?back="+java.net.URLEncoder.encode(backUrl, "utf-8");
			res.sendRedirect(backUrl);
		}else{
			nextFilter.doFilter(request, response);
		}
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		String noFilter = config.getInitParameter("noFilter");
		if(noFilter != null){
			noFilters = noFilter.split(";");
		}
	}

}
